package com.su.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.utils.CRC16;
import com.su.exception.GuiliException;
import com.su.entity.Study;
import com.su.mapper.StudyMapper;
import com.su.service.ClientService;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

@Service
public class ClientServiceImpl extends ServiceImpl<StudyMapper, Study> implements ClientService {


    public static byte[] toByte(String str) {
        if (str == null || str.trim().equals("")) {
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }


    @Override
    public String sendinstruction(Study study) throws IOException {


        byte[] instruct = toByte(study.getInstructioncode());
        int crc = CRC16.calcCrc16(instruct);

        //创建同一连接
//        Socket s = new Socket("172.16.22.209",8001);

        Socket s = new Socket(study.getIpadress(), study.getPort());

        System.out.println("=================>" + s);

        DataOutputStream write = new DataOutputStream(s.getOutputStream());

        System.out.println(instruct);


        write.write(instruct);
        write.write(crc);
        write.write(crc >> 8);


        String ret = "";

        try {

            //封装输入流（接收客户端的流）
            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            DataInputStream read = new DataInputStream(bis);
            byte[] bytes = new byte[1]; // 一次读取一个byte

          //  Thread.sleep(5000);


            while (read.available()==0){
                //循环等待
                System.out.println(read.available() == 0);
            }


            while (read.available() != 0) {

                read.read(bytes);

                ret += bytesToHexString(bytes) + " ";

                System.err.println(ret);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("client is over");
            System.err.println(ret);
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
        String substring1;
        try {
            String substring = ret.substring(8);

            substring1 = substring.substring(0, substring.length() - 6);
        } catch (Exception e) {
            throw new GuiliException(500, "字符串索引超出范围异常警告(自学习开启/关闭异常)");
        }
        return substring1;
    }


    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }


}

